<?php

namespace WsdServer\Lib\Session;

use Illuminate\Support\Arr;
use Illuminate\Support\Str;


class PhpSessionStore extends Store
{
    protected $group;
    public static $SESSION_ID_PREFIX = 'PHPREDIS_SESSION:';

    public function setId($id)
    {
        $this->id = $this->isValidId($id) ? PhpSessionStore::$SESSION_ID_PREFIX.$id : $this->generateSessionId();
    }

    public function setGroup($group){
        $this->group = $group;
    }

    /**
     * Get an item from the session.
     *
     * @param  string  $key
     * @param  mixed  $default
     * @return mixed
     */
    public function get($key, $default = null)
    {
        $data = $this->attributes;
        if ( !empty($this->group) && is_array($data) && key_exists($this->group, $data) ){
            $data = $data[$this->group];
        }
        return Arr::get($data, $key, $default);
    }

    /**
     * Read the session data from the handler.
     *
     * @return array
     */
    protected function readFromHandler()
    {
        $result = [];
        if ($data = $this->handler->read($this->getId())) {
            if ( !empty($this->group) ){
                if (strpos($data, $this->group) == 0){
                    $data = substr($data, strlen($this->group)+1);
                    $result[$this->group] = @unserialize($data);
                }
            } else {
                $result = @unserialize($data);
            }

            if ($result !== false && ! is_null($result) && is_array($result)) {
                return $result;
            }
        }

        return [];
    }

    /**
     * Save the session data to storage.
     *
     * @return void
     */
    public function save()
    {
        $data = serialize($this->attributes);
        if ( !empty($this->group) ) {
           $data = $this->group . '|' . $data['$this->group'];
        }
        $this->handler->write($this->getId(), $data);

        $this->started = false;
    }

    /**
     * Determine if this is a valid session ID.
     *
     * @param  string  $id
     * @return bool
     */
    public function isValidId($id)
    {
        /*
        if ( 0 === strpos($id, PhpSessionStore::$SESSION_ID_PREFIX) ){
            $id = substr($id, str_len(PhpSessionStore::$SESSION_ID_PREFIX)-1);
            if (is_string($id) && ctype_alnum($id) && strlen($id) === 26){
                return true;
            }
        }
        */
        if (is_string($id) && ctype_alnum($id) && strlen($id) === 26) {
            return true;
        }
        return false;
    }

    /**
     * Get a new, random session ID.
     *
     * @return string
     */
    protected function generateSessionId()
    {
        return PhpSessionStore::$SESSION_ID_PREFIX . str::random(26);
    }

}